#!/usr/bin/env python

__Author__ = "Haelwenn Monnier (lanodan) <haelwenn.monnier@gmail.com>"
__License__ = "CC-BY-SA"

import socket, sys, re, time, urllib, subprocess, ConfigParser, os

tetris=0

def get_element(dataInput, elem):
  idx1=dataInput.find('<'+elem+'>')
  idx2=dataInput.find('</'+elem+'>')
  return dataInput[idx1+len('<'+elem+'>'):idx2].strip()

# Output to the channel and console
def printIrc(ircout):
  irc.send('PRIVMSG '+channel+' :'+ircout+'\n')
  print 'PRIVMSG '+channel+' :'+ircout

#line: append to the log (output it to the console too)
def log(line):
  print '[LOG]'+line
  log = open('IRCBot.log', 'a')
  log.write(line+'\n')
  log.close()

urlRegex = re.compile('[hf]t+ps?://')

# Load the config file (config.ini)
config = ConfigParser.ConfigParser()
if (config.read('config.ini')):
  nick       = config.get('Config', 'nick')
  passwd     = config.get('Config', 'passwd')
  server     = config.get('Config', 'server')
  port       = config.get('Config', 'port')
  channel    = config.get('Config', 'channel')
  quitMsg    = config.get('Config', 'quitMessage')
  welcomeMsg = config.get('Config', 'welcomeMessage')
  source     = config.get('Config', 'source')
else:
  print '[ERROR] Couln\'d load config.ini. Example config file: config.ini.example. Exiting'
  sys.exit(1)

irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #defines the socket
irc.connect((server, int(port)))                                                         #connects to the server
irc.send('PASS '+ passwd +'\n')
irc.send('NICK '+ nick +'\n')
irc.send('USER '+ nick +' irc bot :Bot made by lanodan using python!\n') #user authentication
time.sleep(1)
irc.send('JOIN '+ channel +'\n')
printIrc(welcomeMsg)

# Make a while loop to alway parse input
while 1:
  data=irc.recv(2048) # text is the socket input (I use text because input is already taken)
  text=data.lower() # text is the socket input (I use text because input is already taken)
  print data # print the input for debugging purpose

  # Below is a bunch of conditions to see if something the bot can deal with is found

  if text.find('ping') != -1: 
    irc.send('PONG '+data.split()[1]) # Return PONG back (sort of "I'm alive")
  if text.find(':!hi') !=-1:
    printIrc(data.split(':!hi')[1].strip()+': '+welcomeMsg) # split the message received at the :!hi part
  if text.find(':!say') != -1:
    t = data.split(':!say')
    out = t[1].strip()
    printIrc(str(out))
  if text.find(':!action') != -1:
    t = data.split(':!action')
    out = t[1].strip()
    printIrc('\x01ACTION '+out+'\x01') # equivalent of /me
  if urlRegex.search(text) is not None: # Use httpRegex on input
    parse = re.findall('[HhFf][Tt]{1,2}[Pp][Ss]?://[^\{\}\|\\\^\~\[\]\"\'\`\(\)\<\>\ ]+', data) # parse URL
    try:
      url = str(parse[0]).rstrip() # Take the parsed link
      if (len(url) > 8) : # I assume a link is more than 8 characters long
        try:
          get = urllib.urlopen(url) # Open the link
          wget = get.read() # Read the input of the url
          print get.info() # Print Headers
          mimeType = get.info().type # Get the Content-Type
          get.close() # Close the connection
          # find the title
          if wget.find('<title>') != -1:
            title = get_element(wget, 'title')
            printIrc('Title: '+title)
            log(url+'; '+str(mimeType)+'; '+title)
          elif wget.find('<TITLE>') != -1:
            title = get_element(wget, 'TITLE')
            printIrc('Title: '+title)
            log(url+'; '+str(mimeType)+'; '+title)
          #If we can't find the title print the Content-Type
          else:
            printIrc('Type: '+mimeType)
            log(url+'; '+str(mimeType))
        except Exception, e:
          printIrc('Exception: '+str(e))
      else:
        printIrc('Link too short (not more than 8)')
    except Exception, e:
      printIrc('Exception: '+str(e))
  # Output the link to find the source code
  if text.find(':!source') != -1:
    printIrc(source)
  if text.find('kick '+channel+' '+nick) != -1:
    time.sleep(5)
    irc.send('JOIN '+ channel +'\n') #re-join the chan
    printIrc(welcomeMsg) # Say hello
  if text.find('tetris') != -1 and tetris == 0:
    printIrc('Never gonna give you up.')
    printIrc('Never gonna let you down.')
    time.sleep(1)
    printIrc('Never gonna run around and desert you.')
    printIrc('Never gonna make you cry.')
    time.sleep(1)
    printIrc('Never gonna say goodbye.')
    printIrc('Never gonna tell a lie and hurt you.')
    tetris=1 # Prevent another rick roll
  if text.find(':!stop in the name of sey') != -1:
    irc.send('QUIT : '+quitMsg+'\n')
    break # break the loop
  if text == "":
    irc.send('QUIT : Empty socket input\n')
    break # break the loop
irc.close() # Close the socket
sys.exit() # Exit
